<template>
    <div class="jianzhan-content">
        <Crumb :name="$t('workingOrder.workingOrder')"/>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        :placeholder="$t('workingOrder.searchByRequestNo') "
                        prefix-icon="el-icon-search"></el-input>
                <el-input
                        v-model="key1"
                        size="small"
                        class="input"
                        :placeholder="$t('workingOrder.workingNumber') "
                        prefix-icon="el-icon-search"></el-input>
                <el-date-picker v-model="startTime" type="date"  value-format="yyyy-MM-dd" placeholder="Start Time"></el-date-picker>
                <el-date-picker v-model="endTime" type="date"    value-format="yyyy-MM-dd" placeholder="End Time"></el-date-picker>
                <el-button type="primary" icon="el-icon-search"  size="small" @click="search">{{$t('search')}}</el-button>
                <el-button type="primary" icon="el-icon-tickets" size="small" @click="openInvoice">{{$t('invoice.invoice')}}</el-button>
                <el-button type="primary" icon="el-icon-tickets" size="small" @click="downloadAll">{{$t('download')}}</el-button>

            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="workList"
                        border
                        row-key="id"
                        @expand-change="expandChange"
                        @filter-change="filterChange"
                        stripe
                        style="width: 100%"
                >
                    <el-table-column type="expand" :label="$t('workingOrder.problem')" width="80">
                        <template slot-scope="quest">
                            <woDetailExpand :quest="quest.row"></woDetailExpand>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="requestName"
                            :label="$t('workingOrder.requestNo') "
                    ></el-table-column>
                    <el-table-column
                            prop="plateNum"
                            :label="$t('workingOrder.plateNum')"
                    ></el-table-column>
                    <el-table-column
                            prop="workingNo"
                            :label="$t('workingOrder.workingNumber')"
                    ></el-table-column>
                    <el-table-column
                            prop="requestDate"
                            :label="$t('workingOrder.requestDate')"
                    ></el-table-column>

                    <el-table-column
                            column-key="typeCode"
                            prop="serviceType"
                            :filters="serviceTypeFilters"
                            :label="$t('workingOrder.serviceType')"
                    ></el-table-column>
                    <el-table-column
                            column-key="wStatus"
                            prop="woStatusDesc"
                            :label="$t('workingOrder.status')"
                    ></el-table-column>
                    <el-table-column
                            width="250px"
                    >
                        <template slot-scope="request">
                            <el-button-group>
                                <el-button size="mini" type="info" @click="showDetail(request.row)">WO
                                </el-button>
                                <el-button type="danger" size="mini" v-if="!request.row.executionOrNot"
                                           @click="goWoBack(request.row)">{{$t('workingOrder.goBack')}}
                                </el-button>
                                <el-button type="success" size="mini"  v-show="request.row.executionOrNot"><i class="el-icon-tickets"></i></el-button>
                                <!--<el-button type="primary" size="mini" v-if="!request.row.executionOrNot"-->
                                <!--@click="createInvoice(request.row)">{{$t('workingOrder.invoice')}}-->
                                <!--</el-button>-->
                                <!--<el-button type="warning" size="mini" v-else>{{$t('workingOrder.invoice')}}</el-button>-->
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog title="Working Order" :visible.sync="dialogVisible" width="100%" top="0">
            <quest-show :quest="quest"/>
            <div class="spin"></div>
            <el-form label-width="150px" :model="work" :rules="rule" ref="work">
                <div style="display: flex">
                    <div class="flex-content">
                        <el-form-item :label="$t('workingOrder.no')">
                            <el-input v-model="work.workingNo" disabled placeholder="No"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.workingNo')">
                            <el-input v-model="work.workingNumber" size="small" class="my-input"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.date')" prop="startDate">
                            <el-date-picker v-model="work.startDate" size="small" type="datetime" class="my-input"
                                            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                        </el-form-item>

                        <el-form-item :label="$t('workingOrder.actualProblem')">
                            <div class="problem" v-for="(item,index) in work.problemVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <el-input v-model="item.problemDescription" type="textarea" size="small"
                                          class="my-input"></el-input>
                                <el-button @click="showProblem(item,index)" type="warning"
                                           style="width: 20px;height: 20px;padding: 0;vertical-align: middle;margin-left: 10px;margin-bottom: 12px;">
                                    <i class="el-icon-document"></i>
                                </el-button>
                            </div>
                            <el-button @click="addProblem" type="primary"
                                       style="width: 20px;height: 20px;padding: 0;vertical-align: top;position: absolute;top: 15px;right: 0px;">
                                <i class="el-icon-plus"></i>
                            </el-button>
                        </el-form-item>

                        <el-form-item :label="$t('workingOrder.causeOfProblem')">
                            <el-input v-model="work.causeOfProblem" size="small" class="my-input"
                                      placeholder="Cause of problem"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('workingOrder.action')">
                            <div class="problem" v-for="(item,index) in work.suggestionVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <el-input v-model="item.suggestion"
                                          type="textarea"
                                          size="small"
                                          class="my-input"></el-input>
                                <el-button @click="showAction(item,index)"
                                           type="warning"
                                           style="width: 20px;height: 20px;padding: 0;vertical-align: middle;margin-left: 10px;margin-bottom: 12px;">
                                    <i class="el-icon-document"></i>
                                </el-button>
                            </div>
                            <el-button @click="addAction" type="primary"
                                       style="width: 20px;height: 20px;padding: 0;vertical-align: top;position: absolute;top: 15px;right: 0px;">
                                <i class="el-icon-plus"></i>
                            </el-button>
                        </el-form-item>

                    </div>
                    <div class="flex-content">
                        <el-form-item :label="$t('workingOrder.fieldWorkShop')" prop="workingPlace">
                            <el-select v-model="work.workingPlace" size="small" class="my-input">
                                <el-option :value="0" label="Field"></el-option>
                                <el-option :value="1" label="WorkShop"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item :label="$t('workingOrder.stockOutNo')">
                            <el-input v-model="work.suratJalanNo" size="small" class="my-input"></el-input>
                        </el-form-item>
                        <div v-for="(item,idx) in work.jobWorker" :key="idx" class="job-worker">
                            <el-form-item :label="$t('workingOrder.arrayBy')">
                                <el-select v-model="item.arrangedBy"
                                           filterable size="small"
                                           class="my-input">
                                    <el-option v-for="i in employeeList"
                                               :key="i.id"
                                               :value="i.id"
                                               :label="i.employeeName"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('workingOrder.jobReceiver')">
                                <el-select
                                        multiple
                                        filterable
                                        :key="index"
                                        v-model="item.jobReceiver"
                                        class="my-input">
                                    <el-option v-for="employee in employeeList"
                                               :key="employee.id"
                                               :value="employee.id"
                                               :label="employee.employeeName"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('workingOrder.handoverTimer')">
                                <el-date-picker size="small"
                                                class="my-input"
                                                v-model="item.receiverDateStr"
                                                value-format="yyyy-MM-dd HH:mm:ss"
                                                type="datetime"></el-date-picker>
                            </el-form-item>
                            <el-form-item :label="$t('workingOrder.percentage')">
                                <el-input v-model="item.percentage" placeholder="percentage" size="small"
                                          class="my-input"></el-input>
                            </el-form-item>
                            <i class="del el-icon-close" @click="deleteWorker(idx)"></i>
                        </div>
                        <i class="icon el-icon-plus" @click="addJobWorker"></i>


                    </div>
                    <div class="flex-content">

                        <el-form-item :label="$t('workingOrder.woStatus')">
                            <el-select filterable v-model="work.woStatus" size="small" class="my-input">
                                <el-option v-for="item in woStatus"
                                           :key="item.key"
                                           :value="item.key"
                                           :label="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.pendingReason')" v-if="work.woStatus === 2">
                            <el-input v-model="work.pendingReason" placeholder="Reason" size="small"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.endDate')" v-if="(work.woStatus === 3) || (work.woStatus === 4)">
                            <el-date-picker size="small"
                                            v-model="work.endDate"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            type="datetime"></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.pendingStartDate')" v-if="work.woStatus === 2">
                            <el-date-picker size="small"
                                            v-model="work.pendingStartTime"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            :placeholder="$t('workingOrder.pendingStartDate')"
                                            type="datetime"></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.pendingEndDate')" v-if="work.woStatus === 2">
                            <el-date-picker size="small"
                                            v-model="work.pendingEndime"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            :placeholder="$t('workingOrder.pendingEndDate')"
                                            type="datetime"></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.waitingStartDate')" v-if="work.woStatus === 1">
                            <el-date-picker size="small"
                                            v-model="work.waitingStartTime"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            :placeholder="$t('workingOrder.waitingStartDate')"
                                            type="datetime"></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.waitingEndDate')"
                                      v-if="work.woStatus === 1">
                            <el-date-picker size="small"
                                            v-model="work.waitingEndTime"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            :placeholder="$t('workingOrder.waitingEndDate')"
                                            type="datetime"></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.handOver')"  v-if="(work.woStatus === 3) || (work.woStatus === 4)">
                            <el-select v-model="work.handOver"
                                       filterable
                                       placeholder="Hand over"
                                       size="small">
                                <el-option
                                        v-for="item in contactList"
                                        :key="item.contactId"
                                        :label="item.contactName"
                                        :value="item.contactId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('workingOrder.remark')">
                            <el-input type="textarea"
                                      v-model="work.remark"
                                      size="small"
                                      class="my-input"></el-input>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <div class="spin"></div>
            <el-button type="primary"
                       size="small"
                       style="margin: 20px 0;float:left "
                       @click="openPointCode">
                {{$t('workingOrder.addPointCode')}}
                <i class="el-icon-plus"></i>
            </el-button>
            <el-table
                    height="200"
                    :data="pointCodeList"
                    style="width: 100%;clear: both">
                <el-table-column
                        prop="serviceCategory"
                        :label="$t('workingOrder.category')"

                >
                </el-table-column>
                <el-table-column
                        prop="serviceItem"
                        :label="$t('workingOrder.description')"
                >
                </el-table-column>
                <el-table-column
                        prop="hours"
                        :label="$t('workingOrder.hours')"
                >
                </el-table-column>
                <el-table-column
                        prop="pointCode"
                        :label="$t('workingOrder.pointCode')"
                >
                </el-table-column>
                <el-table-column
                        prop="serviceUnit"
                        :label="$t('workingOrder.unit')"
                >
                </el-table-column>
                <el-table-column
                        :label="$t('workingOrder.price')"
                >
                    <template slot-scope="scope">${{scope.row.hours * 100 * 12 / 100}}</template>
                </el-table-column>
                <el-table-column

                >
                    <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" @click="deletePointCode(scope.row)"></el-button>
                    </template>
                </el-table-column>

            </el-table>

            <div class="spin"></div>
            <el-button type="primary" size="small" style="margin: 20px 0;float: left" @click="dbVisible = true">
                {{$t('workingOrder.addParts')}} <i class="el-icon-plus"/></el-button>
            <spDataBase @deleteItem="deleteItem" :partList="partList"/>
            <div class="spin"></div>
            <div>
                <el-input v-model="work.localVendor" placeholder="Local Vendor" size="small" class="input"></el-input>
                <el-currency-input v-model="work.localVendorPrice"
                                   placeholder="Local Vendor Price"
                                   class="input"
                                   :type="10"></el-currency-input>
            </div>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
                        <el-button type="primary" @click="submitForm(1)">{{$t('comfirm')}}</el-button>
                        <el-button type="primary" @click="closeOrder">{{$t('closeOrder')}}</el-button>
                        <el-button type="warning" @click="print">{{$t('print')}}</el-button>
                    </span>
        </el-dialog>
        <el-dialog
                title="Invoice"
                :visible.sync="invoiceVisible"
                width="50%"
        >
            <el-form ref="form1" :model="invoice" label-width="200px">
                <el-form-item
                        :label="$t('workingOrder.invoiceNumber')">
                    <el-input v-model="invoice.invoiceNumber"
                              :placeholder="$t('workingOrder.invoiceNumber')"></el-input>
                </el-form-item>
                <el-form-item
                        :label="$t('workingOrder.startTime')"
                >
                    <el-date-picker v-model="invoice.startTime"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    :placeholder="$t('workingOrder.startTime')"></el-date-picker>
                </el-form-item>
                <el-form-item
                        :label="$t('workingOrder.startTime')"
                >
                    <el-date-picker v-model="invoice.endTime"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    :placeholder="$t('workingOrder.endTime')"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('stockOut.customer')">
                    <el-select v-model="invoice.customer" :placeholder="$t('stockOut.customer')">
                        <el-option
                                v-for="item in customerList"
                                :key="item.id"
                                :label="item.customerName"
                                :value="item.customerName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('workingOrder.invoiceDate')">
                    <el-date-picker v-model="invoice.invoiceDate"
                                    value-format="yyyy-MM-dd"
                                    size="small"
                                    type="date"
                                    :placeholder="$t('workingOrder.invoiceDate')"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('workingOrder.serviceRate')">
                    <el-input v-model="invoice.exchangeRateForPointCode"
                              :placeholder="$t('workingOrder.serviceRate')" size="small"></el-input>
                </el-form-item>
                <el-form-item :label="$t('workingOrder.partRate')">
                    <el-input v-model="invoice.exchangeRateForParts"
                              :placeholder="$t('workingOrder.partRate')" size="small"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="invoiceVisible = false">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="subInvoice">{{$t('confirm')}}</el-button>
          </span>
        </el-dialog>
        <Part-item @close="dbVisible = false" @add="add" :belong-module="belongModule" :visible="dbVisible"/>
        <point-code-dialog ref="pointCode" @selected="selectPointCode"></point-code-dialog>
        <problem :visible="fileShow1" :picture="picture" :video="video" :file="file" @close="close1" @sub="sub1"/>
        <problem :visible="fileShow2" :picture="picture" :video="video" :file="file" @close="close2" @sub="sub2"/>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import spDataBase from '@/components/part/spDataBase'
    import PartItem from '@/components/part/sparePartItem'
    import questShow from '@/components/service/questShow'
    import pointCodeDialog from '@/components/service/pointCodeDialog'
    import woDetailExpand from '@/components/service/woDetailExpand'
    import problem from '@/components/service/problem'

    import {
        getWorkingOrder,
        getEmployeeList,
        showQuestDetail,
        getWorkNo,
        getWorkDetail,
        getRealParts,
        saveWorkingOrder, getContactByCustomer, woGoBack, createSumInvoice, wokingOrderInvoice,
    } from "../../api/service";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import dbMixins from '../../util/spMixins'
    import {arrayUnique, baseURL} from "../../util";
    import {getCustomerList} from "../../api";
    import * as moment from "moment";

    const files = [{
        problemDescription: '',
        problemPhoto: [],
        problemVideo: [],
        problemFile: []
    }];
    const quest = {
        requestNo: '',
        requestDate: '',
        initiator: '',
        customerId: '',
        customerName: '',
        addressId: '',
        address: '',
        distance: '',
        unitModel: '',
        sn: '',
        deliveryTime: '',
        hmKm: '',
        typeCode: '',
        serviceType: "",
        appointmentTime: '',
        note: '',
        status: "",
        projectName: '',
        plateNum: '',
        charges: [],
        reason: '',
        problems: [...files],
        id: '',
    };
    export default {
        name: "working-order",
        mixins: [mixins, dbMixins],
        data() {
            return {
                startTime:'',
                endTime:'',
                wStatus:'',
                typeCode:'',
                customerList: [],
                requestByFilters: [],
                serviceTypeFilters: [
                    {text:"Maintaince",value:1},
                    {text:"Repair",value:2},
                    {text:"Warrenty",value:3},
                    {text:"Tire",value:4},
                ],
                woStatusDescFilters: [
                    {text:"On Progress",value:0},
                    {text:"Waiting For Spareparts",value:1},
                    {text:"Pending",value:2},
                    {text:"Finished",value:3},
                    {text:"Close Order",value:4},
                ],
                belongModule: 3,
                exchangeRateForPointCode: 12000,
                exchangeRateForParts: 2000,
                key: '',
                key1: '',
                quest: {...quest},
                pointCodeList: [],
                priceFactor: 1,
                work: {
                    waitingStartTime: '',
                    waitingEndTime: '',
                    pendingStartTime: '',
                    pendingEndTime: '',
                    workingNumber: '',
                    workingNo: '',
                    woStatus: 0,
                    suratJalanNo: '',
                    salesOrderNo: '',
                    workingPlace: '',
                    continueWoReason: '',
                    continueWoDate: '',
                    continueWoNo: '',
                    startDate: '',
                    endDate: '',
                    handOver: '',
                    remarks: '',
                    pendingReason: '',
                    jobWorker: [
                        {
                            jobReceiver: [],
                            arrangedBy: '',
                            receiverDateStr: '',
                            percentage: '',
                        }
                    ],
                    causeOfProblem: '',
                    problemVoList: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    suggestionVoList: [{suggestion: '', problemPhoto: [], problemVideo: [], problemFile: []}],
                    localVendor: '',
                    localVendorPrice: 0
                },
                fileShow1: false,
                fileShow2: false,
                picture: [],
                video: [],
                file: [],
                rule: {
                    workingPlace: [{required: true, message: 'Working place is required'}],
                    startDate: [{required: true, message: 'Start date is required'}],
                    arrangedBy: [{required: true, message: 'Arranged by is required'}]
                },
                contactList: [],
                list: [],
                employeeList: [],
                dialogVisible: false,
                invoiceVisible: false,
                invoice: {
                    startTime:'',
                    endTime:'',
                    customer:'',
                    invoiceNumber:'',
                    invoiceDate: '',
                    exchangeRateForParts: 2200,
                    exchangeRateForPointCode: 14000
                },

            }
        },
        computed: {
            workList() {
                return this.list
            },
            woStatus() {
                return [
                    {key: 0, value: this.$t('workingOrder.onProgress')},
                    {key: 1, value: this.$t('workingOrder.waitingForSparepart')},
                    {key: 2, value: this.$t('workingOrder.pending')},
                    {key: 3, value: this.$t('workingOrder.finished')},
                    {key: 4, value: this.$t('workingOrder.closeOrder')},
                ]
            }
        },
        created() {
            this._getWorkOrder();
            this._getEmployeeList();
            this._getCustomerList();
        },
        mounted() {
            this.$nextTick(() => {
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            downloadAll(){
                window.open(baseURL+`/manage/working_order/excel_close_order_detail.file?startTime=${this.startTime}&endTime=${this.endTime}`)
                // import('./vendor/export2Excel').then(async excel => {
                //     const tHeader = [
                //         this.$t('workingOrder.requestNo'),
                //         this.$t('workingOrder.plateNum'),
                //         this.$t('workingOrder.workingNumber'),
                //         this.$t('workingOrder.requestDate'),
                //         this.$t('workingOrder.serviceType')];
                //     const filterVal = ['requestNo', 'plateNum', 'workingNo', 'requestDate', 'serviceType'];
                //     const {status,data} = await getWorkingOrder({pageSize:10000,woStatus:4});
                //     let d = [];
                //     if(status === ERROR_OK) {
                //          d = this.formatJson(filterVal, data.list);
                //     } else {
                //         this.$message.error('下载超时');
                //         return
                //     }
                //     excel.export_json_to_excel({
                //         header: tHeader,
                //         data:d,
                //         filename: 'Close Order' + moment().format('YYYY-MM-DD'),
                //         autoWidth: true,
                //         bookType: 'xlsx'
                //     })
                // })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]

                }))
            },
            filterChange(column){
                this.pageNum = 1;
                Object.keys(column).forEach(item=>{
                    this[item] = column[item][0]
                });
                this._getWorkOrder()
            },
            openInvoice(){
                this.invoiceVisible = true;
            },
            async _getCustomerList() {
                const {status, data} = await getCustomerList(3);
                if (status === ERROR_OK) {
                    this.customerList = data
                }
            },
            clear1() {
                this.invoice = {
                    startTime:'',
                    endTime:'',
                    customer:'',
                    invoiceNumber:'',
                    invoiceDate: '',
                    exchangeRateForParts: 2200,
                    exchangeRateForPointCode: 14000
                }
            },
            async subInvoice() {
                if (!this.invoice.invoiceNumber) {
                    this.$message.error('Invoice Number is empty');
                    return
                }
                if (!this.invoice.exchangeRateForParts) {
                    this.$message.error('请填写汇率');
                    return
                }
                if (!this.invoice.exchangeRateForPointCode) {
                    this.$message.error('请填写汇率');
                    return
                }
                const {startTime,endTime,customer,invoiceNumber,exchangeRateForPointCode, exchangeRateForParts, invoiceDate} = this.invoice;
                const {status, msg} = await createSumInvoice({
                    exchangeRateForPointCode,
                    exchangeRateForParts,
                    startTime,
                    endTime,
                    customer,
                    invoiceNumber,
                    invoiceDate
                });
                if (status === ERROR_OK) {
                    this.$message.success('开票成功');
                    this._getWorkOrder();
                    this.clear1()
                } else {
                    this.$message.error(msg)
                }
                this.invoiceVisible = false;
            },

            async expandChange(row) {
                if (row.partList) {
                    return
                }
                const {status, data} = await getWorkDetail(row.workingId);
                if (status === ERROR_OK) {
                    this.$set(row, 'workingNumber', data.workingNumber)
                    this.$set(row, 'jobInformationVoList', data.jobInformationVoList)
                    this.$set(row, 'serviceChargeList', data.serviceChargeList)
                    this.$set(row, 'suggestionVoList', data.suggestionVoList)
                    this.$set(row, 'causeOfProblem', data.causeOfProblem)
                    this.$set(row, 'workingPlaceDesc', data.workingPlaceDesc)
                    this.$set(row, 'problemVoList', data.problemVoList)
                    if (data.partsList) {
                        const partList = data.partsList.map(part => {
                            return {
                                ...part,
                                number: part.quantity,
                                quantity: part.sparePartsStock,
                            }
                        });
                        this.$set(row, 'partList', partList)
                    }


                }
            },
            //TODO 订单回撤
            async goWoBack(row) {
                const {status} = await woGoBack(row.workingId);
                if (status === ERROR_OK) {
                    this.$message.success('Revoke Success');
                    this._getWorkOrder();
                }
            },
            deleteWorker(idx) {
                if (this.work.jobWorker.length === 1) {
                    return;
                } else {
                    this.work.jobWorker.splice(idx, 1)
                }
            },
            handleFilter(value, row, column) {
                const property = column['property'];
                return row[property] === value;
            },
            deletePointCode(row) {
                const targetIdx = this.pointCodeList.findIndex(item => item.id === row.id);
                this.pointCodeList.splice(targetIdx, 1);
            },
            selectPointCode(list) {
                this.pointCodeList = this.pointCodeList.concat(list)
            },
            openPointCode() {
                this.$refs.pointCode.open()
            },
            closeOrder() {
                if (this.work.woStatus !== 3) {
                    this.$notify.error('Work Status must be finished');
                    return;
                }
                this.$confirm('Do you want to CLOSE THIS ORDER', 'Attention', {
                    confirmButtonText: 'Confirm',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(() => {
                    this.submitForm(2)
                }).catch(() => {

                });
            },
            close1() {
                this.fileShow1 = false
            },
            close2() {
                this.fileShow2 = false
            },
            sub1(file) {
                const current = {...this.current, ...file};
                this.work.problemVoList.splice(this.index, 1, current);
                this.close1();
            },
            sub2(file) {
                const current = {...this.current, ...file};
                this.work.suggestionVoList.splice(this.index, 1, current);
                this.close2();
            },
            showProblem(item, index) {
                this.picture = item.problemPhoto;
                this.video = item.problemVideo;
                this.file = item.problemFile;
                this.current = item;
                this.index = index;
                this.fileShow1 = true
            },
            showAction(item, index) {
                this.picture = item.problemPhoto;
                this.video = item.problemVideo;
                this.file = item.problemFile;
                this.current = item;
                this.index = index;
                this.fileShow2 = true
            },
            addProblem() {
                this.work.problemVoList.push({
                    problemDescription: '',
                    problemPhoto: [],
                    problemVideo: [],
                    problemFile: []
                })
            },
            addAction() {
                this.work.suggestionVoList.push({photo: [], video: [], file: [], suggestion: ''})
            },
            async submitForm(origin) {
                if (origin !== 1) {
                    origin = 2
                }
                let {
                    waitingStartTime,
                    waitingEndTime,
                    pendingStartTime,
                    pendingEndTime,
                    workingNumber,
                    workingNo,
                    startDate,
                    workingPlace,
                    suratJalanNo,
                    unit,
                    category,
                    pendingReason,
                    endDate,
                    handOver,
                    woStatus,
                    orderId,
                    jobWorker,
                    remarks,
                    localVendor,
                    localVendorPrice,
                    causeOfProblem
                } = this.work;
                let problem = this.work.problemVoList;
                const newProblem = [];
                problem.forEach(item => {
                    newProblem.push({
                        problemDescription: item.problemDescription,
                        problemPhoto: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        problemFile: item.problemFile ? item.problemFile.join(',') : '',
                        problemVideo: item.problemVideo ? item.problemVideo.join(',') : ''
                    })
                });
                let suggestion = this.work.suggestionVoList;
                const newSuggestion = [];
                suggestion.forEach(item => {
                    newSuggestion.push({
                        suggestion: item.suggestion,
                        photo: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        video: item.problemVideo ? item.problemVideo.join(',') : '',
                        file: item.problemFile ? item.problemFile.join(',') : ''
                    })
                });
                const j = JSON.parse(JSON.stringify(jobWorker));
                j.forEach(item => {
                    item.jobReceiver = item.jobReceiver.join(',')
                });
                let job = JSON.stringify(j);


                let serviceChargeItem = this.pointCodeList.map(item => {
                    return item.id
                });
                serviceChargeItem = serviceChargeItem.join(',');
                let sparePartsList = this.partList.map(part => {
                    return {
                        partsId: part.id,
                        partsQuantity: part.number
                    }
                });
                sparePartsList = JSON.stringify(sparePartsList);
                this.$refs.work.validate(async valid => {
                    if (valid) {
                        const {status, msg} = await saveWorkingOrder({
                            origin,
                            waitingStartTime,
                            waitingEndTime,
                            pendingStartTime,
                            pendingEndTime,
                            workingNumber,
                            workingNo,
                            startDate,
                            unit,
                            category,
                            pendingReason,
                            endDate,
                            handOver,
                            remarks,
                            workingPlace,
                            suratJalanNo,
                            woStatus,
                            orderId,
                            jobWorker: job,
                            serviceChargeItem,
                            sparePartsList,
                            localVendor,
                            localVendorPrice,
                            causeOfProblem,
                            problem: JSON.stringify(newProblem),
                            suggestion: JSON.stringify(newSuggestion),
                        });
                        if (status === ERROR_OK) {
                            this.$message.success('Success');
                            this.dialogVisible = false;
                            this._getWorkOrder();
                            this.clear();
                        } else {
                            this.$notify.error(msg);
                        }
                    }
                })
            },
            async _getWorkOrder() {
                const {status, data} = await getWorkingOrder({
                    pageNum: this.pageNum,
                    requestNo: this.key,
                    workingNo:this.key1,
                    startTime:this.startTime,
                    endTime:this.endTime,
                    typeCode:this.typeCode,
                    woStatus:4,
                });
                if (status === ERROR_OK) {
                    this.list = data.list;
                    this.total = data.total;
                }
            },
            search() {
                this.pageNum = 1;
                this._getWorkOrder()
            },
            changePage(page) {
                this.pageNum = page;
                this._getWorkOrder()
            },
            async getCustomerContact(name) {
                const {status, data} = await getContactByCustomer(name);
                if (status === ERROR_OK) {
                    this.contactList = data;
                }
            },
            async _getEmployeeList() {
                const {status, data} = await getEmployeeList();
                if (status === ERROR_OK) {
                    this.employeeList = data
                }
            },
            addJobWorker() {
                this.work.jobWorker.push({
                    jobReceiver: [],
                    arrangedBy: '',
                    receiverDateStr: ''

                })
            },
            async _getDetail(id) {
                const {status, data} = await showQuestDetail(id);
                if (status === ERROR_OK) {
                    this.quest = data.orderVo;
                    if (data.problemVoList.length) {
                        this.$set(this.quest, 'problems', data.problemVoList);
                    } else {
                        this.$set(this.quest, 'problems', [{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                    this.priceFactor = data.orderVo.priceFactor;
                    this.getCustomerContact(this.quest.customerName);
                    this.quest.problems = data.problemVoList

                }
            },


            async _getWorkNo() {
                const {status, data} = await getWorkNo();
                if (status === ERROR_OK) {
                    this.work.workingNo = data
                }
            },
            async _getRealPart(workOrderNo) {
                const {status, data} = await getRealParts(workOrderNo);
                if (status === ERROR_OK) {
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity
                        }
                    })
                } else {
                    this.partList = []
                }
            },
            async _getWorkDetail(row) {
                const {status, data} = await getWorkDetail(row.workingId);
                if (status === ERROR_OK) {
                    this.work = data;
                    if (!data.problemVoList) {
                        this.$set(this.work, 'problemVoList', [{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                    if (!data.jobWorker) {
                        this.$set(this.work, 'jobWorker', [
                            {
                                jobReceiver: [],
                                arrangedBy: '',
                                receiverDateStr: '',
                                percentage: '',

                            }
                        ])
                    } else {
                        data.jobWorker = JSON.parse(data.jobWorker);
                        data.jobWorker.forEach(item => {
                            if (item.jobReceiver) {
                                item.jobReceiver = item.jobReceiver.split(',').map(j => parseInt(j, 10));
                            }
                        });
                        this.$set(this.work, 'jobWorker', data.jobWorker);
                    }
                    if (!data.suggestionVoList) {
                        this.$set(this.work, 'suggestionVoList', [{
                            suggestion: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    } else {
                        const suggestion = data.suggestionVoList.map(item => {
                            return {
                                suggestion: item.suggestion,
                                problemPhoto: item.photo,
                                problemVideo: item.video,
                                problemFile: item.file
                            }
                        })
                        this.$set(this.work, 'suggestionVoList', suggestion)
                    }
                    this.$set(this.work, 'jobReceiver', data.jobReceiverVoList);
                    if (data.partsList) {
                        this.partList = data.partsList.map(part => {
                            return {
                                ...part,
                                number: part.quantity,
                                salesPrice: part.priceFactor * (part.temPriceCHN || part.temPriceIDR),
                                quantity: part.sparePartsStock,
                            }
                        });
                    }

                    if (data.serviceChargeList) {
                        const serviceChargeList = data.serviceChargeList.map(item => {
                            return {
                                ...item,
                                price: item.hours
                            }
                        });
                        this.pointCodeList = serviceChargeList
                    }

                }
            },
            clear() {
                this.work = {
                    waitingStartTime: '',
                    waitingEndTime: '',
                    pendingStartTime: '',
                    pendingEndTime: '',
                    workingNo: '',
                    woStatus: 0,
                    suratJalanNo: '',
                    salesOrderNo: '',
                    workingPlace: '',
                    continueWoReason: '',
                    continueWoDate: '',
                    continueWoNo: '',
                    startDate: '',
                    endDate: '',
                    handOver: '',
                    remarks: '',
                    pendingReason: '',
                    jobWorker: [
                        {
                            jobReceiver: [],
                            arrangedBy: '',
                            receiverDateStr: '',
                            percentage: '',
                        }
                    ],
                    causeOfProblem: '',
                    problemVoList: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    suggestionVoList: [{suggestion: '', problemPhoto: [], problemVideo: [], problemFile: []}],
                    localVendor: '',
                    localVendorPrice: 0
                }
                this.partList = [];
                this.pointCodeList = [];

            },
            showDetail(work) {
                this._getDetail(work.id);
                if (!work.workingNo) {
                    this.clear();
                    this._getWorkNo();
                    this.partList = [];
                } else {
                    this._getWorkDetail(work);
                }
                this.dialogVisible = true;
                this.work.orderId = work.id
            },
            print() {
                let parts = '';
                let mart = '';
                let receiver = '';
                let arrangedBy = '';
                let point = '',
                    hours = '';
                this.partList.filter(item => {
                    return (item.category === 1) || (item.category === 2)
                }).forEach((part, index) => {
                    parts += `${index + 1} .${part.partsNumber}  ${part.number}PC  ${part.denomination}/${part.designation}\n`
                });
                this.partList.filter(item => {
                    return (item.category === 3) || (item.category === 4)
                }).forEach((part, index) => {
                    mart += `${index + 1} .${part.partsNumber}  ${part.number}PC  ${part.denomination}/${part.designation}\n`
                });
                this.pointCodeList.forEach((item, index) => {
                    point += `${index + 1} .${item.pointCode}  ${item.serviceItem}\n`
                    hours += `${index + 1} .${item.hours}\n`
                });
                if (this.work.jobInformationVoList) {
                    this.work.jobInformationVoList.forEach((item, i) => {
                        receiver += `Group${i + 1}:\n`;
                        arrangedBy += `Group${i + 1}:\n${item.arrangeByName}\n`;
                        if (item.jobReceiverName) {
                            item.jobReceiverName.forEach((j) => {
                                receiver += `${j}\n`
                            })
                        }
                    });
                }

                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 20],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '70%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT LINE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        },
                                        ' No.17-18 Blok A, Ruko Inkopal Kelapa Gading \n',
                                        ' Jl. Boulevard Barat Raya Jakarta Utara 14240 Indonesia \n',
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'Working Order',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, -10, 20, 20],
                            columns: [
                                {
                                    width: '*',
                                    text: [
                                        `Date: ${this.quest.requestDate.substr(0, 10)}\n`,
                                        `Service Request: ${this.quest.requestNo}\n`,
                                        `Working Order : ${this.work.workingNo}\n`,
                                        `Surat Jalan: ${this.work.suratJalanNo}`
                                    ],
                                    alignment: 'right'
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows: 0,
                                style: 'column',
                                widths: ['50%', '50%'],
                                heights: [150, 150],
                                body: [
                                    [
                                        `Customer:${this.quest.customerName}\nRequest Date:${this.quest.requestDate}\nRequest By:${this.quest.requestBy}\nOperate:${this.quest.operatorName}\nContact No:\n`,
                                        `Unit model:${this.quest.unitModel}\nSn:${this.quest.sn}\nHour Meter:${this.quest.hmKm}\nDelivery Date:${this.quest.deliveryTime}\nJob Type:${this.quest.serviceType}\nProblem Description:`
                                    ]
                                ]
                            }
                        },
                        {
                            margin: [0, 20, 0, 0],
                            table: {
                                headerRows: 0,
                                style: 'column',
                                widths: ['50%', '50%'],
                                heights: [100, 100],
                                body: [
                                    [
                                        `Point Code:\n${point}`,
                                        `Hours:\n${hours}`
                                    ]
                                ]
                            }
                        },
                        {
                            width: '*',
                            text: 'Spareparts',
                            alignment: 'left'
                        },
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows: 0,
                                style: 'column',
                                widths: ['100%'],
                                heights: [100],
                                body: [
                                    [
                                        parts
                                    ]
                                ]
                            }
                        },
                        {
                            width: '*',
                            text: 'Materials',
                            alignment: 'left'
                        },
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows: 0,
                                style: 'column',
                                widths: ['100%'],
                                heights: [100],
                                body: [
                                    [
                                        mart
                                    ]
                                ]
                            }
                        },
                        {
                            margin: [30, 0, 0, 0],
                            alignment: 'center',
                            columns: [
                                {
                                    width: '25%',
                                    text: [
                                        `Receiver Order\n`,
                                        receiver
                                    ],

                                },
                                {
                                    width: '25%',
                                    text: [
                                        'Giving Order\n',
                                        arrangedBy
                                    ]
                                },
                                {
                                    width: '25%',
                                    text: 'Customer Pic',
                                },
                                {
                                    width: '*',
                                    text: [
                                        'Operater\n',
                                        this.quest.operatorName
                                    ]
                                }
                            ],
                        },
                        {
                            margin: [0, 30, 0, 0],
                            text: [
                                `Start Wo  :${this.work.startDate}\n`,
                                `Finish Wo:${this.work.endDate}\n`,
                            ]
                        }

                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh'
                    },

                    styles: {
                        header: {
                            fontSize: 15,
                            bold: true
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 25,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                };
                this.pdf.open(doc);
            }
        },
        components: {
            Crumb, Search, spDataBase, PartItem, questShow, pointCodeDialog, problem, woDetailExpand
        },

    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .job-worker {
        position: relative;
        border-bottom: 1px solid #ddd;
        border-right: 2px dashed #eee;
        border-left: 1px dashed #eee;
        border-top: 1px solid #ddd;
        padding-top: 15px;
        .del {
            top: 0;
            right: 0;
            cursor: pointer;
            position: absolute;
            border-radius: 50%;
            background: #ddd;
            color: white;
            display: none;
        }
        &:hover {
            .del {
                display: block;
                &:hover {
                    background: #3a8ee6;
                }
            }
        }

    }

    .icon {
        background: #3a8ee6;
        color: white;
        padding: 5px;
        cursor: pointer;
        border-radius: 50%;
        margin-top: 10px;
    }

    .spin {
        border-bottom: 2px dashed #ddd;
        width: 100%;
        height: 0;
        margin-top: 20px;
    }
</style>